/**
 * User: 蕨菜
 * Date: 2019-05-22
 * Time: 16:17
 * Description: 此文件简要说明
 */


const {
    Student,
    Class,
    Grade
} = require('../../models');

const {
    AppUtil
} = require('../../util');

module.exports = async function updateStudent(body, ctx) {

    const {
        id,
        name,
        phone,
        sex,
        studentId,
        father,
        fatherPhone,
        mother,
        motherPhone,
        address,
        active,
        gradeYear: year,
        classId,
    } = body;

    await Student.update({
        name,
        phone,
        sex,
        studentId,
        father,
        fatherPhone,
        mother,
        motherPhone,
        address,
        active,
    }, { where: { id } })

    const studentInstance = Student.findByPk(id);
    if (AppUtil.isEmpty(year)) {
        const gradeId = await studentInstance.get('gradeId');
        if (!AppUtil.isEmpty(gradeId)) {
            const gradeInstance = await Grade.findByPk(gradeId)
            await gradeInstance.setStudents(null);
        }

    }

    if (AppUtil.isEmpty(classId)) {
        // 更新的时候把班级去掉了,就要对该用户所关联的classId进行删除
        const classId = await studentInstance.get('classId');
        // 如果之前绑定过class就删除, 没绑定过没有删除的必要
        if (!AppUtil.isEmpty(classId)) {
            const classInstance = await Grade.findByPk(classId)
            await classInstance.setStudents(null);
        }
    }

    if (!AppUtil.isEmpty(year)) {
        const gradeInstance = await Grade.findOne({
            where: {
                year
            }
        });
        gradeInstance.setStudents(id);
    }

    if (!AppUtil.isEmpty(classId)) {
        const classInstance = await Class.findByPk(classId);
        classInstance.setStudents(id);
    }

    const data = await Student.findByPk(studentInstance.id);
    return ctx.body = {
        success: true,
        data
    }

}